package com.tiyende.kash.loop.ui.presenter

import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.base.BaseFragment
import com.tiyende.kash.loop.common.CommonPresenter
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.request.IHttpCallback
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.fragment.TiyendeOrderRepayListFragment
import com.tiyende.kash.loop.ui.fragment.TiyendeWithdrawFragment
import com.tiyende.kash.loop.utils.helper.TiyendeOrderHelper
import com.tiyende.kash.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.kash.loop.utils.helper.TiyendeStatusHelper
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 11:59
 * @Annotation：主页面 Presenter 实现
 */
class TiyendeMainPresenter(private val iView: IViewContract.ITiyendeMainView): CommonPresenter(iView) {
    private val tabIconSList = arrayListOf(
        R.mipmap.tiyende_main_home_icon,
        R.mipmap.tiyende_main_repay_icon
    )
    private val tabTitleList = arrayListOf(
        R.string.tiyende_main_withdraw,
        R.string.tiyende_main_repay
    )
    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    private val fragments = ArrayList<BaseFragment>()
    //首次进入APP，存在待还款订单需要跳转到待还款列表
    var isFirstIn = true

    //授信接口上次请求时间戳，防止3秒内重复请求
    private var requestCreditLastTime = 0L

    /**
     * 加载Tabbar数据
     */
    fun queryTiyendeMainTabList(){
        tabList.clear()
        //tab
        for (i in 0 until tabTitleList.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabIcon", tabIconSList[i])
            tabObj.put("tabTitle", getString(tabTitleList[i]))
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        iView.showTiyendeMainList(tabList)
    }

    /**
     * 加载FragmentList
     */
    fun queryTiyendeMainFragmentList(){
        fragments.add(TiyendeWithdrawFragment())//首页
        fragments.add(TiyendeOrderRepayListFragment())//还款
        setMainCurrentItemIndex(0)
    }

    /**
     * 切换Tab
     */
    fun setMainCurrentItemIndex(index: Int) {
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                index -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        iView.notifyTiyendeMainDataChanged(index)

        val fragment = fragments[index]
        iView.showTiyendeMainFragment(fragment,index)
    }

    /**
     * 获取总流程
     */
    fun queryTiyendeProcessAction() {
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_PROCESS_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Account Info")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Aadhaar Card")
//                    allStepTitles.put("PAN Card")
//                    allStepTitles.put("Face recognition")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("account_info")
//                    allSteps.put("ocr_info")
//                    allSteps.put("aadhaar_card_info")
//                    allSteps.put("pan_card_info")
//                    allSteps.put("sefie_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    steps.put("ocr_info")
//                    steps.put("aadhaar_card_info")
//                    steps.put("pan_card_info")
//                    steps.put("sefie_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    //保存用户流程数据
                    TiyendeProcessHelper.saveTiyendeAuthenticationData(obj)

                    // 上次请求授信接口的时间是否超过3秒
                    val isRequestCredit = System.currentTimeMillis() - requestCreditLastTime > 3000
                    //进件信息已完成 - 需要授信状态完成之后通知 刷新进件信息
                    if (TiyendeProcessHelper.queryTiyendeAuthenticationStepList().isEmpty() && isRequestCredit){
                        queryTiyendeCreditStatusAction()
                    } else {//进件信息 未完成 - 直接通知刷新进件信息完成
                        iView.hiddenTiyendeLoading()
                        //通知全局流程刷新完成
                        iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED))
                    }

                    // TODO: 2024-11-20 新增需求 此处需要判断是否需要校验手机号
                    if (TiyendeProcessHelper.isTiyendeAuthenticationCheckMobile()){
                        iView.hiddenTiyendeLoading()
                        iView.showTiyendeMainMustCheckMobilePage()
                        return
                    }
                    // TODO: 2025-08-21 新增需求 ，风控审核中
                    if (TiyendeProcessHelper.queryTiyendeGuideLocalType() == "REVIEWING"){
                        iView.hiddenTiyendeLoading()
                        iView.showTiyendeMainReviewingPage()
                        return
                    }
                    // TODO:  2025-08-21 新增需求 ，进入引导页
                    if (TiyendeProcessHelper.queryTiyendeGuideLocalType() == "GUIDE"){
                        iView.hiddenTiyendeLoading()
                        iView.showTiyendeMainGuideLocalPage()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取授信状态
     * status:
     *  PASSED(跳过该流程)
     *  REJECTED(跳拒绝页面)
     *  CREATED(可再次请求)
     */
    fun queryTiyendeCreditStatusAction(){
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_CREDIT_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    requestCreditLastTime = System.currentTimeMillis()
                    val creditStatus = obj.optString("status")
                    TiyendeStatusHelper.saveTiyendeCreditStatus(creditStatus)
                    //刷新流程信息完成
                    iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED))
                    //通知全局授信状态刷新完成
                    iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_CREDIT_REFRESHED))
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取订单列表
     */
    fun queryTiyendeOrderListAction(){
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_LOAN_ORDER_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //保存当前时间戳,用于计算待还款订单剩余时长
                    obj.put("timeStamp",data.optLong("timp"))
                    TiyendeOrderHelper.saveTiyendeOrderData(obj)

                    val repayList = TiyendeOrderHelper.queryTiyendeOrderRepayList()
                    //存在待还款订单 ，切换到待还款tab
                    if (repayList.size > 0 && isFirstIn){
                        isFirstIn = false
                        iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_SHOW_REPAY))
                    }
                    //通知全局订单刷新完成
                    iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESHED))
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.getAct().publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_FINISHED))
            }
        })
    }
}